const app = getApp();
const utils = require('../../utils/util.js');
var wxpay = require('../../utils/pay.js');
Page({

  data: {
    CurrentPage: 1,
    loadingMore: 1,
    createUid: 0, //带货人ID   
    model: 2,   //1 商家编辑模式, 2 用户购买模式
    version: 5, //供货商列表版本： 5 云点单, 6 云代货
    staffList: [],
    userInfo:{},
    cardInfo:{},
    versionid: 5, //要升级的版本
    canIUseGetUserProfile: false,
    navBarHeight: 44,
    payDialog: {isshow: false,ispay: false,title1: "",title2: "",submittext: "",isupdate: 5},
    meituan: {
      pagePath: '',    //外卖链接
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.removeStorageSync('shipInfo');
    this.initParam(options);
    if(this.data.version == '6'){
      wx.setNavigationBarTitle({title: '云代货'})
    }
    if(!this.data.createUid || this.data.createUid <= 0){
      utils.showModal('缺少商家id'); return;
    }
    this.getStaff();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    if(app.globalData.userInfo){
      that.data.userInfo = app.globalData.userInfo;
    }else {
      setTimeout(function () {
        that.onShow();
      }.bind(that), 1000)
    }
  },

  initParam: function(options){  
    if (options.q) {    //扫二维码进来的
      let pArray = this.getParamArray(options.q);    
      wx.setStorageSync("cardId", pArray[0]);
      this.setData({
        createUid: pArray[1],
        model: pArray[2],
        version: pArray[3],
        navBarHeight: app.globalData.navBarHeight
      });
    } else{
      if(options.isShare && options.id){
        wx.setStorageSync('cardId', options.id);  //通过分享进来的
      }
      this.setData({
        createUid: options.createUid,
        model: options.model ? options.model : 1,
        version: options.version,
        navBarHeight: app.globalData.navBarHeight
      })    
    }
  },
  //获取二维码参数
  getParamArray: function(url){ 
    url = decodeURIComponent(url);
    let params = url.substr(url.indexOf('?') + 1);
    let plist = '';  
    if (params.indexOf('p-') != -1) {
      let param = params.match(/p-(\S*)/)[1];   //url格式：www.711688.com/?p-1_2_3
      plist = param.split('_');
    } 
    return plist;
  },
  //供货商列表
  getSupplyList: function () {    
    let that = this;
    utils.getLocation((location)=>{
      let supplyState = that.data.model == 1 ? 0 : 1;
      wx.request({
        url: app.globalData.host + '/api/supply/GetList',
        data:{
          joinState: 1,
          saleUid: that.data.createUid,
          version: that.data.version,
          supplyState: supplyState,
          latitude:  location.lat,
          longitude: location.lng,
          page:  that.data.CurrentPage
        },
        success: function (res) {      
          if (res.data.Code != 0) {       
            utils.showModal(res.data.Message); return;      
          }
          let staffList =  that.data.staffList; //营业中的商家
          let staffList2 = [];                  //已打烊商家
          //删除已打烊商家
          for(let i = 0;i < staffList.length; i++){
            if(staffList[i].WorkState == 1){
              staffList2.push(staffList[i]);    
              staffList.splice(i,1);         
              i--;     
            }
          }
          for (let i = 0; i < res.data.Data.Items.length; i++) {         
            let item = res.data.Data.Items[i];
            item.Avater = utils.formatAvater(item.Avater, 'https://static.711688.net.cn/upload/card/source/');           
            item.ShowDiscount = item.Discount / 10;
            item.Distance = parseFloat(item.Distance).toFixed(2);
            item.Distances = parseFloat(item.Distance / 1000).toFixed(2);  
            if(item.WorkState == 0){
              staffList.push(item);
            }else{
              staffList2.push(item)
            }
          }
          //追加已打烊商家
          staffList.push.apply(staffList,staffList2);    
          that.setData({
            staffList: staffList,
            loadingMore: res.data.Data.TotalPages
          })  
        }
      })
    });    
  },
  // 加载更多
  loadMore: function () {
    let that = this;
    if (that.data.loadingMore > 1 && that.data.CurrentPage < that.data.loadingMore) {
      let page = that.data.CurrentPage + 1
      that.setData({
        CurrentPage: page
      })
      that.getSupplyList();
    } 
  },
  //删除供货商
  delete: function(e){
    let that = this;
    let uid = e.currentTarget.dataset.uid;
    wx.request({
      url: app.globalData.host + '/api/supply/DeleteSupply?saleUid='+ app.globalData.userInfo.Uid + '&uid=' + uid ,
      success: function (res) {      
        if (res.data.Code != 0) {      
          utils.showModal(res.data.Message); return;      
        }
        utils.showToast('操作成功');
        that.getSupplyList();
      }
    })
  },
  //设置供货状态
  setState: function(e){
    let that = this;
    let uid = e.currentTarget.dataset.uid;
    let state = e.currentTarget.dataset.state;
    wx.request({
      url: app.globalData.host + '/api/supply/setState?saleUid='+ app.globalData.userInfo.Uid + '&uid=' + uid + '&state=' + state ,
      success: function (res) {      
        if (res.data.Code != 0) {      
          utils.showModal(res.data.Message); return;      
        }
        utils.showToast('操作成功');
        that.getSupplyList();
      }
    })
  },
  //添加供货商
  toAdd: function(){
    let that = this;
    wx.redirectTo({
      url: '/merchant/supply/add/index?createUid='+ that.data.createUid + '&version=' + that.data.version,
    })
  },

  //跳转页面
  toCardDetail: function(e){
    let that = this;
    let staffid = e.currentTarget.dataset.staffid; 
    let uid = e.currentTarget.dataset.uid; 
    let staffList = this.data.staffList;   
    let workState = 0;
    for(var i=0;i<staffList.length;i++){
      if(staffList[i].Id == staffid){
        workState = staffList[i].WorkState;
        break;
      }
    }
    if(workState == 1 && this.data.model == 2){
      utils.showToast('不在营业时间内');
      return;
    }
    let url = '/merchant/supply/productList/index?uid=' + uid;
    if(this.data.model == 2){
      url = '/pages/product/classes/index?supplyUid=' + uid + '&version=' + that.data.version;
    }
    if(this.data.createUid == uid){
      url ='/pages/product/classes/index'
    }
    wx.navigateTo({url: url})
  },
  getStaff: function(){
    let that =this;
    let cardId = wx.getStorageSync('cardId');
    wx.request({
      url: app.globalData.host + '/api/staff/GetInfo?id=' + cardId,
      success: function (res) {            
        if (res.data.Code == 0) {   
          that.getSupplyList();
          that.setData({
            cardInfo:{CardInfo: res.data.Data}
          })
        }
      },
    })   
  },
  //升级弹框
  showPayDialog: function () {
    let industryCode =this.data.cardInfo.CardInfo.IndustryCode;
    let userInfo = this.data.userInfo;
    let payDialog = this.data.payDialog;
    let version = this.data.version;  //5 云点单商家, 6 云代货商家
    payDialog.isshow = true;
    payDialog.ispay = true,
    payDialog.title1 = "升级云点单版本才能使用";
    payDialog.submittext = "立即升级";           
    if (app.globalData.platform == 'ios') {
      payDialog.ispay = false;
      payDialog.submittext = "发送升级申请";
    }
    
    if(industryCode == 3 || industryCode == 5  || industryCode == 6){
      payDialog.isshow = false;
    }
    this.setData({
      userInfo: userInfo,
      payDialog: payDialog
    })
  },
  
  //关闭注册玖玖客弹框
  dialogsState: function () {
    let {
      payDialog
    } = this.data;
    if (payDialog.isshow) {
      payDialog.isshow = false;
    } else {
      payDialog.isshow = true;
    }
    this.setData({
      payDialog: payDialog
    })
  },
  // 创建名片时1选择共享推广版4智慧经营版
  versionSelect: function (e) {
    let versionid = e.currentTarget.dataset.versonid;
    let payDialog = this.data.payDialog;
    if (versionid == 1) {
      payDialog.submittext = '立即创建';
    }
    if (versionid == 4) {
      if (app.globalData.platform == 'ios') {
        payDialog.submittext = "发送升级申请";
        if (this.data.showAi) {
          payDialog.submittext = "发送续费申请"
        }
      } else {
        payDialog.submittext = "立即升级";
        if (this.data.showAi) {
          payDialog.submittext = "立即续费";
        }
      }      
    }
    this.setData({
      versionid: versionid,
      payDialog: payDialog,
    })
  },
   //创建支付安卓手机,苹果手机发送申请(授权头像昵称)
   creatMyCardPay: function (e) {
    let that = this;
    let isAccredit = that.data.isAccredit;
    if (e.detail.iv) {
      that.toCreatMyCardPay();
    } else {
      utils.showToast('请授权微信头像、昵称');
    }
  },

  //创建支付安卓手机,苹果手机发送申请(先授权微信头像昵称)===用户授权api修改
  creatMyCardPayByfile: function () {
    let that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('用于完善会员资料', res);
        utils.AuthorizeUserInfo(res, '', function (flag) {
          if (flag) {
            that.toCreatMyCardPay();
          } else {//注册失败，重新点击授权
            wx.login({
              success: function (res) {
                that.data.loginCode = res.code;
              }
            })
          }
        });
      },
      fail: (err) => {
        utils.showModal('请授权微信头像、昵称');     
      }
    })
  },

  //创建支付安卓手机,苹果手机发送申请
  toCreatMyCardPay: function (e) {
    var that = this;
    var cardInfo = that.data.cardInfo.CardInfo;   
    if (app.globalData.platform != 'ios' || that.data.versionid == 1) {
      wxpay.createStaffOrder(app, cardInfo.Id, that.data.versionid);
      utils.aiCardActionRecord(24);
    } else {
      //发送创建申请
      that.createStaffPayRequest(that.data.versionid);
    }
  },

  //申请代付
  applyCardPay: function (e) {
    var that = this;
    let isAccredit = that.data.isAccredit;
    if (e.detail.iv) {
      that.createStaffPayRequest(that.data.versionid);
    } else {
      utils.showModal('请授权微信头像、昵称');
    }
  },

  //申请代付===用户授权api修改
  applyCardPayByfile: function () {
    var that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('用于完善会员资料', res);
        utils.AuthorizeUserInfo(res, '', function (flag) {
          if (flag) {
            that.createStaffPayRequest(that.data.versionid);
          }
        });
      },
      fail: (err) => {
        utils.showModal('请授权微信头像、昵称');
      }
    })
  },

  //申请代付
  createStaffPayRequest: function (versionid) {
    let that = this;
    var cardInfo = that.data.cardInfo.CardInfo;
    wx.showLoading({title: '申请中',mask: true})
    wx.request({
      url: app.globalData.host + '/api/Staff/CreateStaffPayRequest?fromUid=' + app.globalData.userInfo.Uid + '&toUid=' + cardInfo.Uid + '&industryCode=' + versionid,
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          utils.showToast('申请成功!');
          that.dialogsState();
        } else {       
          utils.showModal(res.data.Message)
        }
      }
    })
  },

  //跳转美团
  toMeituan: function(){
    let that = this;
    that.getMeitunLink(()=>{
       if(!that.data.meituan.pagePath){
         utils.showToast('美团链接加载失败, 请重试');
         return;
       }
       wx.navigateToMiniProgram({appId: 'wxde8ac0a21135c07d',path: that.data.meituan.pagePath})
     })
   },
   getMeitunLink: function(callback){
     let that = this;
     if(that.data.meituan.pagePath){
       callback();
       return;
     }
     wx.request({
       url: app.globalData.host + '/api/meituan/getLink?uid=' + app.globalData.userInfo.Uid,
       success: function (res) {
         if (res.data.Code == 0) {          
           that.data.meituan.pagePath = res.data.Data;
           callback();
         }
       }
     })
   },
  
   /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    let that = this;
    let cardInfo = that.data.cardInfo.CardInfo;
    let path = '/merchant/supply/list/index?model=2&isShare=1&createUid=' + that.data.createUid + '&id=' + cardInfo.Id + '&version='  + that.data.version;
    console.log(path)
    return {
      imageUrl: cardInfo.Slides,
      title: cardInfo.Company,
      path: path,
      success: function (res) {
        utils.showToast('分享成功');
      }
    }
  },
  onReachBottom: function () {
    this.loadMore();
  },
})